package com.aitaoxue.palx.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.aitaoxue.palx.AppContext;
import com.aitaoxue.palx.R;
import com.aitaoxue.palx.adapter.PullOrderAdapter;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseListFragment;
import com.aitaoxue.palx.base.ListBaseAdapter;
import com.aitaoxue.palx.bean.ListEntity;
import com.aitaoxue.palx.bean.RobOrder;
import com.aitaoxue.palx.bean.SearchParent;
import com.aitaoxue.palx.bean.SearchParentList;
import com.aitaoxue.palx.db.GoodDBHelper;
import com.aitaoxue.palx.db.InfoDBHelper;
import com.aitaoxue.palx.ui.RockOrderDetailActivity;
import com.aitaoxue.palx.ui.empty.EmptyLayout;
import com.aitaoxue.palx.util.GsonUtil;
import com.aitaoxue.palx.widget.RevealLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class PullOrderFragment extends BaseListFragment {

	private String CACHE_KEY_PREFIX = "pull_order_";

	private HashMap<String, String> params = null;

	// 注意这里可能为空
	private String cityId = null;

	// 城市
	protected RevealLayout first;
	protected TextView city;
	// 科目
	protected RevealLayout second;
	protected TextView course;
	// 薪资
	protected RevealLayout third;
	protected TextView price;
	// 性别
	protected RevealLayout fourth;
	protected TextView sex;

	protected ImageView notifyBtn;

	private LayoutInflater inflater;

	// private Animation pop_in;
	// private Animation pop_out;

	private void setCacheKey(String key) {
		CACHE_KEY_PREFIX = key;
	}

	@Override
	protected String getCacheKeyPrefix() {
		if (CACHE_KEY_PREFIX == null) {
			return null;
		} else {
			return CACHE_KEY_PREFIX + cityId;
		}
	}

	@Override
	public void initView(View view) {
		first = (RevealLayout) view.findViewById(R.id.layout_first);
		second = (RevealLayout) view.findViewById(R.id.layout_second);
		third = (RevealLayout) view.findViewById(R.id.layout_third);
		fourth = (RevealLayout) view.findViewById(R.id.layout_fourth);
		city = (TextView) view.findViewById(R.id.city);
		course = (TextView) view.findViewById(R.id.course);
		price = (TextView) view.findViewById(R.id.price);
		sex = (TextView) view.findViewById(R.id.sex);

		notifyBtn = (ImageView) view.findViewById(R.id.choose_btn);

		params = new HashMap<String, String>();
		cityId = AppContext.getInstance().getProperty("user.cityid");

		super.initView(view);

		first.setOnClickListener(this);
		second.setOnClickListener(this);
		third.setOnClickListener(this);
		fourth.setOnClickListener(this);
		notifyBtn.setOnClickListener(this);

		inflater = LayoutInflater.from(getActivity());
		// pop_in = AnimationUtils.loadAnimation(getActivity(),
		// R.anim.popup_in);
		// pop_out = AnimationUtils.loadAnimation(getActivity(),
		// R.anim.popup_out);
	}

	@Override
	protected ListBaseAdapter getListAdapter() {
		return new PullOrderAdapter();
	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_pull_order;
	}

	@Override
	protected void sendRequestData(Map<String, String> map) {
		if (map == null) {
			map = params;
		}
		map.put("city_id", cityId);

		AitaoXueApi.searchParentV1(String.valueOf(mCurrentPage), map, mhandler);
	}

	@Override
	protected ListEntity parseList(byte[] response) throws Exception {
		String res = new String(response);

		SearchParentList list = GsonUtil
				.GsonToBean(res, SearchParentList.class);

		return list;
	}

	@Override
	protected SearchParentList readList(Serializable seri) {
		return (SearchParentList) seri;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.layout_first: // 城市
			final PopupWindow window = new PopupWindow(getActivity());
			final View cityView = inflater.inflate(R.layout.popup_window_city,
					null);
			window.setWidth(LayoutParams.MATCH_PARENT);
			window.setHeight(LayoutParams.WRAP_CONTENT);
			window.setContentView(cityView);
			window.setFocusable(true);
			window.setOutsideTouchable(true);
			window.setAnimationStyle(R.style.popup_anim);

			TextView cityXian = (TextView) cityView
					.findViewById(R.id.city_xian);
			TextView cityChendu = (TextView) cityView
					.findViewById(R.id.city_chendu);
			cityXian.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					window.dismiss();

					city.setText("西安");
					int id = InfoDBHelper.getCityId("西安市");
					cityId = String.valueOf(id);
					refreshData(params);
				}
			});
			cityChendu.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					window.dismiss();

					city.setText("成都");
					int id = InfoDBHelper.getCityId("成都市");
					cityId = String.valueOf(id);
					refreshData(params);
				}
			});
			window.showAsDropDown(first);
			break;
		case R.id.layout_second:
			final PopupWindow window2 = new PopupWindow(getActivity());
			final View courseView = inflater.inflate(
					R.layout.popup_window_course, null);
			window2.setWidth(LayoutParams.MATCH_PARENT);
			window2.setHeight(LayoutParams.WRAP_CONTENT);
			window2.setContentView(courseView);
			window2.setFocusable(true);
			window2.setOutsideTouchable(true);
			window2.setAnimationStyle(R.style.popup_anim);

			ListView listview1 = (ListView) courseView.findViewById(R.id.cate);
			HashMap<String, String> map = GoodDBHelper.getAllCate();

			ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(
					getActivity(), android.R.layout.simple_list_item_1,
					new ArrayList<String>(map.values()));
			listview1.setAdapter(adapter2);
			ListView listView2 = (ListView) courseView.findViewById(R.id.kind);
			final ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(
					getActivity(), android.R.layout.simple_list_item_1);
			listView2.setAdapter(adapter3);
			listView2.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					String course = adapter3.getItem(position);
					// Toast.makeText(getActivity(), course,
					// Toast.LENGTH_SHORT).show();

					window2.dismiss();
					params.put("good_kind_name", course);
					setCacheKey(null);
					refreshData(params);
				}
			});

			listview1.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					List<String> kinds = GoodDBHelper.getKindByCate(String
							.valueOf(position + 1));

					adapter3.clear();
					adapter3.addAll(kinds);

					adapter3.notifyDataSetChanged();
				}
			});

			window2.showAsDropDown(first);

			break;
		case R.id.layout_third:
			final PopupWindow window3 = new PopupWindow(getActivity());
			final View priceView = inflater.inflate(
					R.layout.popup_window_price, null);
			window3.setWidth(LayoutParams.MATCH_PARENT);
			window3.setHeight(LayoutParams.WRAP_CONTENT);
			window3.setContentView(priceView);
			window3.setFocusable(true);
			window3.setOutsideTouchable(true);
			window3.setAnimationStyle(R.style.popup_anim);

			ListView listView = (ListView) priceView
					.findViewById(R.id.listview);
			String[] items = new String[] { "0-30", "30-60", "60-90", "90-120",
					"120-150", "150-180", "180以上" };
			final ArrayAdapter<String> adapter4 = new ArrayAdapter<String>(
					getActivity(), android.R.layout.simple_list_item_1, items);
			listView.setAdapter(adapter4);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					String prices = adapter4.getItem(position);

					String[] price = null;

					price = prices.split("-");

					if (price.length == 2) {
						params.put("price_start", price[0]);
						params.put("price_stop", price[1]);
					} else {
						params.put("price_start", "180");
					}

					setCacheKey(null);
					refreshData(params);
					window3.dismiss();
				}
			});

			window3.showAsDropDown(first);
			break;
		case R.id.layout_fourth:
			final PopupWindow window4 = new PopupWindow(getActivity());
			final View sexView = inflater.inflate(R.layout.popup_window_sex,
					null);
			window4.setWidth(LayoutParams.MATCH_PARENT);
			window4.setHeight(LayoutParams.WRAP_CONTENT);
			window4.setContentView(sexView);
			window4.setFocusable(true);
			window4.setOutsideTouchable(true);
			window4.setAnimationStyle(R.style.popup_anim);

			ListView sexListView = (ListView) sexView
					.findViewById(R.id.sex_list);
			String[] list = new String[] { "不限", "男", "女" };
			ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
					android.R.layout.simple_list_item_1, list);
			sexListView.setAdapter(adapter);

			sexListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					switch (position) {
					case 0:
						sex.setText("性别");
						if (params.containsKey("sex")) {
							params.remove("sex");
						}
						break;
					case 1:
						sex.setText("男");
						params.put("sex", "1");
						break;
					case 2:
						sex.setText("女");
						params.put("sex", "0");
						break;
					}

					setCacheKey(null);
					refreshData(params);
					window4.dismiss();
				}
			});

			window4.showAsDropDown(first);
			break;
		case R.id.choose_btn:
			HashMap<Integer, Boolean> ids = ((PullOrderAdapter) mAdapter)
					.getMap();

			if (ids.size() == 0) {
				Toast.makeText(getActivity(), "请选择客户后再联系", Toast.LENGTH_SHORT)
						.show();
			} else {
				Set<Integer> set = ids.keySet();
				List<RobOrder> tmp = new ArrayList<RobOrder>();
				for (Integer i : set) {
					if (ids.get(i)) {
						tmp.add(new RobOrder(((SearchParent) mAdapter
								.getItem(i)).getRequirement_id()));
					}
				}

				String jsonStr = GsonUtil.ListToJson(tmp);

				AitaoXueApi.connectParentList(jsonStr, mConnectHandler);
			}

			break;
		default:
			break;
		}
	}

	private void refreshData(Map<String, String> map) {
		mListView.setSelection(0);
		mCurrentPage = 1;
		mState = STATE_REFRESH;
		mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
		requestData(true, map);
	}

	private AsyncHttpResponseHandler mConnectHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String res = new String(arg2);

			try {
				JSONObject json = new JSONObject(res);
				String code = json.getString("code");
				if (code.equals("0000")) {
					((PullOrderAdapter) mAdapter).clear();
					refreshData(params);
					Toast.makeText(getActivity(), "联系成功", Toast.LENGTH_SHORT)
							.show();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {

		}
	};

	public void onItemClick(android.widget.AdapterView<?> parent, View view,
			int position, long id) {
		Intent intent = new Intent(getActivity(), RockOrderDetailActivity.class);
		SearchParent detail = (SearchParent) mAdapter.getItem(position);
		intent.putExtra("detail", detail);
		startActivity(intent);
	};

}
